package com.daervin.svc.common.utils;

import okhttp3.*;

/**
 * @author daervin
 * @date 2019/10/24
 */
public final class HttpClientUtil {
    private HttpClientUtil() {
    }

    private static OkHttpClient okHttpClient = new OkHttpClient();

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static Response post(String url, String param, Headers headers) {
        Response response = null;
        try {
            RequestBody requestBody = RequestBody.create(JSON, param);
            Request.Builder builder = new Request.Builder()
                    .url(url);
            if (headers != null) {
                builder.headers(headers);
            }
            Request request = builder.post(requestBody)
                    .build();
            Call call = okHttpClient.newCall(request);
            response = call.execute();
        } catch (Exception e) {
            System.err.println("HttpClient-POST" + e.getMessage());
        }
        return response;
    }

    public static Response get(String url) {
        Response response = null;
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Call call = okHttpClient.newCall(request);
            response = call.execute();
        } catch (Exception e) {
            System.err.println("HttpClient-GET" + e.getMessage());
        }
        return response;
    }
}
